package 并发编程.自定义FutureTask;

import java.util.concurrent.*;

public class App {
    /*考虑到多线程时，用线程池，提高运行效率
     */
    static ExecutorService executorService = Executors.newCachedThreadPool();


    public static void main(String args[]) throws ExecutionException, InterruptedException {
        long t1 = System.currentTimeMillis();
        /*
         * 并行调用服务，减少服务器响应时间
         * */
        Callable<String> stringCallable1 = new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "hello";
            }
        };
        Callable<String> stringCallable2 = new Callable<String>() {
            @Override
            public String call() throws Exception {
                TimeUnit.SECONDS.sleep(10);
                return "world";
            }
        };
        MyFutureTask<String> stringMyFutureTask1 = new MyFutureTask<>(stringCallable1, "task1");
        MyFutureTask<String> stringMyFutureTask2 = new MyFutureTask<>(stringCallable2, "task2");
        //又返回用submit 不需要返回用 execute
        executorService.submit(stringMyFutureTask1);

        executorService.submit(stringMyFutureTask2);
        System.out.println("stringMyFutureTask1 = " + stringMyFutureTask1.get());
        System.out.println("stringMyFutureTask2 = " + stringMyFutureTask2.get());
        long t2 = System.currentTimeMillis() - t1;
        System.out.println("总时长" + t2);
    }

}
